import { DataRecord } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import formidable, { File } from "formidable";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

const prisma = new PrismaClient();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "GET") {
    res.status(200).json(await getDataRecordList(req));
  } else if (req.method === "POST") {
    res.status(200).json(await createDataRecord(req));
  }
}

// 获取数据记录列表
async function getDataRecordList(req: NextApiRequest) {
  const dataRecords = await prisma.dataRecord.findMany();
  return dataRecords;
}

// 创建数据记录
async function createDataRecord(req: NextApiRequest) {
  const form = formidable({});
  const [fields, files] = await form.parse(req);

  // 创建记录
  try {
    const dataRecord = await prisma.dataRecord.create({
      data: { name: fields.name![0] },
    });
    upload(files.image![0]);
    return { code: 200, message: "创建数据记录成功", data: dataRecord };
  } catch (err) {
    console.log(err);
    return { code: 500, message: "创建数据记录失败" };
  }
}

// 上传文件
export function upload(file: File) {
  const uploadDir = path.join(process.cwd(), "upload");
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
  }
  const targetPath = path.join(uploadDir, file.originalFilename!);
  copyFile(file.filepath!, targetPath);
}

// 复制文件
function copyFile(sourcePath: string, targetPath: string) {
  const sourceStream = fs.createReadStream(sourcePath);
  const targetStream = fs.createWriteStream(targetPath);
  sourceStream.pipe(targetStream);
}

export const config = {
  api: {
    bodyParser: false,
  },
};
